<template>
	<view>
		<view class="cu-bar bg-white">
			<view class="action">
				图片上传
			</view>
			<view class="action">
				{{imgList.length}} / {{max}}
			</view>
		</view>
		<input type="text" :name="bizType" :value="imageListStr" hidden>
		<input type="text" :name="imageDel" :value="imageDelListStr" hidden>
		<view class="cu-form-group">
			<view class="grid col-4 grid-square flex-sub">
				<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index].fileUrl">
				 <image :src="imgList[index].fileUrl" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg(index)" :data-index="index">
						<text class='cuIcon-close'></text>
					</view>
				</view>
				<view class="solids" @tap="ChooseImage">
					<text class='cuIcon-cameraadd'></text>
				</view>
			</view>
			<view ref="input" class="input" hidden="true"></view>
		</view>
	</view>
</template>

<script>
	import {mapState, mapMutations} from 'vuex'
	export default {
		name: 'js-input',
		behaviors: ['uni://form-field-group'],
		props:{
			bizType: {
				type: String,
				default: ''
			},
			imageDel: {
				type: String,
				default: ''
			},
			max:{
				type: String,
				default: 4
			},
			bizKey: {
				type: String,
				default: ''
			}
		},
		data(){
			return {
				imgList: [],
				needDel: []
			}
		},
		computed:{
			...mapState(["HOST_URL", "__sid"]),
			imageListStr(){
				// 需要上传的图片
				let imgs = []
				this.imgList.forEach((v, k)=>{
					imgs.push(v.id)
				})
				return imgs.join(",")
			},
			imageDelListStr(){
				// 需要删除的图片
				return this.needDel.join(",")
			}
		},
		mounted() {
			// H5端图片上传
			// #ifdef H5
			var that = this;
			var input = document.createElement('input');
			input.type = 'file';
			input.id = 'imagesAll';
			input.accept = 'image/*';
			input.style.display = 'none';
			input.onchange = event => {
				that.uploadImgH5();
			};
			this.$refs.input.$el.appendChild(input);
			// #endif
			// 显示默认的图片
			if(this.bizKey){
				this.$request({
					url: "a/file/fileList",
					data: {
						bizKey: this.bizKey,
						bizType: this.bizType
					},
					success:(res)=>{
						if(res.data.length){
							res.data.forEach((v, k)=>{
								v.fileUrl = this.HOST_URL + v.fileUrl;
							})
							this.imgList = this.imgList.concat(res.data)
						}
						uni.hideLoading()
					}
				})
			}
		},
		methods:{
			ChooseImage() {
				// #ifdef H5
				document.getElementById('imagesAll').click();
				// #endif
				// #ifdef APP-PLUS || MP-WEIXIN
				let that = this
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						// 循环上传每一张图片
						// 开始上传选中的图片
						res.tempFilePaths.forEach((value, ind)=>{
							that.startUpload(value, res.tempFiles[ind].size);
						})
					}
				});
				// #endif
			},
			// 微信/APP文件上传
			startUpload(res, size) {
					console.log(this.__sid)
					var that = this;
					var rnd = new Date().getTime() + this.__sid;
					
					// 获取文件后缀名
					var index1 = res.lastIndexOf('.');
					var index2 = res.length;
					console.log(res)
					var suffix = res.substring(index1, index2); //后缀名
					
					console.log(suffix)
					
					uni.showLoading({
						title: '上传中...',
						icon: 'none'
					});
					console.log(this.HOST_URL + '/a/file/upload?__ajax=json&__sid=' + that.__sid)
					uni.uploadFile({
						url: this.HOST_URL + '/a/file/upload?__ajax=json&__sid=' + that.__sid,
						filePath: res,
						name: 'file',
						formData: {
							fileMd5: rnd,
							bizKey: '',
							bizType: 'testData_image',
							uploadType: 'image',
							imageMaxWidth: 1024,
							imageMaxHeight: 768,
							__ajax: 'json',
							fileName: rnd + suffix,
							id: 'WU_FILE_0',
							name: rnd + suffix,
							type: 'image/' + suffix.replace('.', ''),
							size: size
						},
						success: res => {
							console.log(res)
							let result = JSON.parse(res.data);
							if(result.result == "login"){
								that.autoLogin().then(function(){
									that.uploadImg(res, size);
								})
							}
							if (result.result == 'true') {
								result.fileUpload.fileUrl = that.HOST_URL + result.fileUpload.fileUrl;
								var obj = {};
								obj.id = result.fileUpload.id;
								obj.fileUrl = result.fileUpload.fileUrl;
								console.log(obj.fileUrl)
								that.imgList.push(obj);
							}else {
								uni.showModal({
									title: '提示',
									content: result.message,
									showCancel: false,
									cancelText: '',
									confirmText: '确定',
									success: res => {},
									fail: () => {},
									complete: () => {}
								});
							}
							console.log(imgList)
						},
						fail: err => {
							uni.showToast({
								title: "上传失败",
								icon: 'none'
							})
							console.log('fail');
							console.log(JSON.stringify(err));
						},
						complete: complete => {
							uni.hideLoading();
							console.log('complete');
							console.log(complete);
						}
					});
			},
			ViewImage(e){
				let arr = [];
				this.imgList.forEach(data => {
					arr.push(data.fileUrl);
				});
				uni.previewImage({
					urls: arr,
					current: e.currentTarget.dataset.url
				});
			},
			// H5文件上传
			uploadImgH5() {
				uni.showLoading({
					title: '上传中...',
					mask: false
				});
				// #ifdef H5
				var fData = new FormData();
				let imagesAll = document.getElementById('imagesAll');
				var index1 = imagesAll.value.lastIndexOf('.');
				var index2 = imagesAll.value.length;
				var suffix = imagesAll.value.substring(index1, index2); //后缀名
				fData.append('file', imagesAll.files[0]);
				fData.append('fileMd5', new Date().getTime() + this.__sid);
				fData.append('bizKey', '');
				fData.append('bizType', 'testData_image');
				fData.append('uploadType', 'image');
				fData.append('imageMaxWidth', 1024);
				fData.append('imageMaxHeight', 768);
				fData.append('fileName', new Date().getTime() + this.__sid + suffix);
				fData.append('id', 'WU_FILE_0');
				fData.append('name', new Date().getTime());
				fData.append('type', 'image/' + suffix.replace('.', ''));
				fData.append('size', imagesAll.size);
				var xhr = new XMLHttpRequest();
				xhr.open('POST', this.HOST_URL + '/a/file/upload?__ajax=json&__sid=' + this.__sid, true);
				let that = this;
				xhr.onreadystatechange = function() {
					console.log(xhr.readyState);
					if (xhr.readyState == 4) {
						var result = JSON.parse(xhr.responseText);
						if (result.result == 'true') {
							result.fileUpload.fileUrl = that.HOST_URL + result.fileUpload.fileUrl;
							var obj = {};
							obj.id = result.fileUpload.id;
							obj.fileUrl = result.fileUpload.fileUrl;
							that.imgList.push(obj);
							imagesAll.value = '';
							uni.hideLoading()
						}else {
							uni.showModal({
								title: '提示',
								content: result.message,
								showCancel: false,
								cancelText: '',
								confirmText: '确定',
								success: res => {},
								fail: () => {},
								complete: () => {}
							});
						}
					}
				};
				//上传成功
				xhr.send(fData);
				// #endif
			},
			// 图片删除
			DelImg(ind) {
				console.log(ind)
				uni.showModal({
					title: '',
					content: '确定要删除吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							let obj = this.imgList.splice(ind, 1);
							this.needDel.push(obj[0].id);
						}
					}
				});
			}
		}
	}
</script>

<style>
</style>
